package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import cn.roco.quicksearch.util.SearchAdapter;

import com.badibadi.abcpinying.SortModel;
import com.badibadi.activity.ChatActivity;
import com.badibadi.activity.ChatSettingActivity;
import com.badibadi.activity.GroupManagementActivity;
import com.badibadi.activity.PinyinSeeOtherPeopleFriendActivity;
import com.badibadi.infos.Results;
import com.badibadi.infos.TypeId;
import com.badibadi.infos.friendShow_Model;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.socket.Send_Geshi_Tool;
import com.badibadi.uniclubber.R;
import com.google.zxing.oned.rss.FinderPattern;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.PaoPao_Button;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class AfterLandingMyHomePageMyFriendsFragment extends BaseFragment {

	private ExpandableListView elv;
	private MyFriendsFragmentAdapter mAdapter;
	private ImageView after_landing_my_friends_chacha;
	private Results results2;
	private List<friendShow_Model> show_Models, show_Models_sousuo;
	private List<SortModel> friends_main;
	private AutoCompleteTextView search;
	private SearchAdapter adapter = null;//
	private boolean jud = false;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:
				Utils.ExitPrgress(getActivity());
				try {
					Send_Geshi_Tool.show_Models_Public = show_Models;
					mAdapter.notifyDataSetChanged();
					for (int i = 0; i < show_Models.size(); i++) {
						if (show_Models.get(i).getFriends() != null
								&& show_Models.get(i).getFriends().size() > 0) {
							friends_main
									.addAll(show_Models.get(i).getFriends());
						}
					}
					friends_main = shaixuan(friends_main);
					jud = true;
					search.setThreshold(1);

					adapter = new SearchAdapter<SortModel>(
							getActivity(),
							R.layout.after_landing_my_friends_adapter_child_import_layout,
							friends_main, SearchAdapter.ALL);// 速度优先
					search.setAdapter(adapter);//
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(
				R.layout.fragment_after_landing_my_friends, null);
		init(view);
		return view;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (jud) {
			friendShow();
		}
	}

	private List<SortModel> shaixuan(List<SortModel> friends_main) {
		for (int i = 0; i < friends_main.size() - 1; i++) {
			for (int j = friends_main.size() - 1; j > i; j--) {
				if (friends_main.get(j).getId()
						.equals(friends_main.get(i).getId())) {
					friends_main.remove(j);
				}
			}
		}
		return friends_main;
	}

	private void init(View view) {
		// TODO Auto-generated method stub
		show_Models = new ArrayList<friendShow_Model>();
		show_Models_sousuo = new ArrayList<friendShow_Model>();
		friends_main = new ArrayList<SortModel>();
		elv = (ExpandableListView) view
				.findViewById(R.id.after_landing_my_friends_expandableListView1);
		search = (AutoCompleteTextView) view
				.findViewById(R.id.after_landing_my_friends_searchcontent);
		after_landing_my_friends_chacha = (ImageView) view
				.findViewById(R.id.after_landing_my_friends_chacha);
		after_landing_my_friends_chacha
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						search.setText("");
					}
				});
		search.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

			}
		});
		mAdapter = new MyFriendsFragmentAdapter();
		elv.setAdapter(mAdapter);
		friendShow();
	}

	private void friendShow() {
		Utils.showPrgress(getActivity());
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(getActivity()));
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "chat/friendShow");
				if (content != null) {
					results2 = Utils.checkResult_NNN(getActivity(), content);
					//    ("用户分组列表+朋友返回参数是:" + content);
//					   
					if (results2 != null
							&& !results2.getRetmsg().equals("null")
							&& results2.isRet()) {
						try {
							show_Models = JSONUtils.getListByJsonString(
									results2.getRetmsg(),
									friendShow_Model.class);
							handler.sendEmptyMessage(2);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	/**
	 * 可以展开的好友列表：需要 1.父列表视图， 2.子列表视图， 3.图片灰色化处理， 4.是否在线 ， 5.需要知道是否是手机在线，
	 * 6.泡泡消息的处理，
	 * 
	 * @author Administrator
	 * 
	 */
	class MyFriendsFragmentAdapter extends BaseExpandableListAdapter {
		private DisplayImageOptions options;

		public MyFriendsFragmentAdapter() {
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.ic_stub)
					.showImageForEmptyUri(R.drawable.noimage)
					.showImageOnFail(R.drawable.noimage).cacheInMemory()
					.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
					.build();
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			LayoutInflater inflater = LayoutInflater.from(getActivity());
			convertView = inflater.inflate(
					R.layout.after_my_friends_adapter_group, null);
			TextView my_friends_group_infos = (TextView) convertView
					.findViewById(R.id.my_friends_group_infos);
			my_friends_group_infos.setText(show_Models.get(groupPosition)
					.getType()
					+ " ("
					+ show_Models.get(groupPosition).getCountLogin()
					+ "/"
					+ show_Models.get(groupPosition).getCountFriend() + ")");
			return convertView;
		}

		@Override
		public int getGroupCount() {
			// TODO Auto-generated method stub
			return show_Models.size();
		}

		@Override
		public View getChildView(final int groupPosition,
				final int childPosition, boolean isLastChild, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			LayoutInflater inflater = LayoutInflater.from(getActivity());
			convertView = inflater
					.inflate(
							R.layout.after_landing_my_friends_adapter_child_import_layout,
							null);
			ImageView paoPaoButton1 = (ImageView) convertView
					.findViewById(R.id.paoPaoButton1);
			ImageView child_is_login = (ImageView) convertView
					.findViewById(R.id.child_is_login);
			ImageLoader.getInstance().displayImage(
					Constants.BadiDownImgUrl
							+ show_Models.get(groupPosition).getFriends()
									.get(childPosition).getHead()
							+ Constants.appPhoto4img, paoPaoButton1, options);
			TextView child_name = (TextView) convertView
					.findViewById(R.id.child_name);
			TextView child_qianming = (TextView) convertView
					.findViewById(R.id.child_qianming);
			child_name.setText(show_Models.get(groupPosition).getFriends()
					.get(childPosition).getNickName());
			child_qianming.setText(show_Models.get(groupPosition).getFriends()
					.get(childPosition).getMotto());
			if (show_Models.get(groupPosition).getFriends().get(childPosition)
					.getIs_login().equals("1")) {
				child_is_login
						.setImageResource(R.drawable.shape_blue_circular_bead);
			} else {
				child_is_login
						.setImageResource(R.drawable.shape_gray_circular_bead);
			}
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub

					if (show_Models.get(groupPosition).getIs_blacklist() != null
							&& show_Models.get(groupPosition).getIs_blacklist()
									.equals("0")) {
						Intent intent = new Intent(getActivity(),
								ChatActivity.class);
						intent.putExtra("id", show_Models.get(groupPosition)
								.getFriends().get(childPosition).getId());
						intent.putExtra("name", show_Models.get(groupPosition)
								.getFriends().get(childPosition).getNickName());
						intent.putExtra("head", show_Models.get(groupPosition)
								.getFriends().get(childPosition).getHead());
						startActivity(intent);
					} else if (show_Models.get(groupPosition).getIs_blacklist() != null
							&& show_Models.get(groupPosition).getIs_blacklist()
									.equals("1")) {
						Intent intent = new Intent(getActivity(),
								ChatSettingActivity.class);
						intent.putExtra("fid", show_Models.get(groupPosition)
								.getFriends().get(childPosition).getId());
						startActivity(intent);
					}else{
						Intent intent = new Intent(getActivity(),
								ChatActivity.class);
						intent.putExtra("id", show_Models.get(groupPosition)
								.getFriends().get(childPosition).getId());
						intent.putExtra("name", show_Models.get(groupPosition)
								.getFriends().get(childPosition).getNickName());
						intent.putExtra("head", show_Models.get(groupPosition)
								.getFriends().get(childPosition).getHead());
						startActivity(intent);
					}
				}
			});
			// paoPaoButton1.setMessage(99);
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			// TODO Auto-generated method stub
			if (show_Models.get(groupPosition).getFriends() != null) {
				return show_Models.get(groupPosition).getFriends().size();
			} else {
				return 0;
			}
		}

		@Override
		public Object getChild(int arg0, int arg1) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getChildId(int arg0, int arg1) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public Object getGroup(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getGroupId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean isChildSelectable(int arg0, int arg1) {
			// TODO Auto-generated method stub
			return false;
		}
	}

	// private class SouSuo_MyFriendsFragmentAdapter extends BaseAdapter {
	// private DisplayImageOptions options;
	//
	// public SouSuo_MyFriendsFragmentAdapter() {
	// options = new DisplayImageOptions.Builder()
	// .showStubImage(R.drawable.ic_stub)
	// .showImageForEmptyUri(R.drawable.noimage)
	// .showImageOnFail(R.drawable.noimage).cacheInMemory()
	// .cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
	// .build();
	// }
	//
	// @Override
	// public int getCount() {
	// // TODO Auto-generated method stub
	// return friends_main.size();
	// }
	//
	// @Override
	// public Object getItem(int arg0) {
	// // TODO Auto-generated method stub
	// return friends_main.get(arg0);
	// }
	//
	// @Override
	// public long getItemId(int arg0) {
	// // TODO Auto-generated method stub
	// return arg0;
	// }
	//
	// @Override
	// public View getView(final int arg0, View convertView, ViewGroup arg2) {
	// // TODO Auto-generated method stub
	// LayoutInflater inflater = LayoutInflater.from(getActivity());
	// convertView = inflater
	// .inflate(
	// R.layout.after_landing_my_friends_adapter_child_import_layout,
	// null);
	// ImageView paoPaoButton1 = (ImageView) convertView
	// .findViewById(R.id.paoPaoButton1);
	// ImageView child_is_login = (ImageView) convertView
	// .findViewById(R.id.child_is_login);
	// ImageLoader.getInstance()
	// .displayImage(
	// Constants.BadiDownImgUrl
	// + friends_main.get(arg0).getHead(),
	// paoPaoButton1, options);
	// TextView child_name = (TextView) convertView
	// .findViewById(R.id.child_name);
	// TextView child_qianming = (TextView) convertView
	// .findViewById(R.id.child_qianming);
	// child_name.setText(friends_main.get(arg0).getNickName());
	// child_qianming.setText(friends_main.get(arg0).getMotto());
	// if (friends_main.get(arg0).getIs_login().equals("1")) {
	// child_is_login
	// .setImageResource(R.drawable.shape_blue_circular_bead);
	// } else {
	// child_is_login
	// .setImageResource(R.drawable.shape_gray_circular_bead);
	// }
	// convertView.setOnClickListener(new OnClickListener() {
	// @Override
	// public void onClick(View arg5) {
	// // TODO Auto-generated method stub
	// Intent intent = new Intent(getActivity(),
	// ChatActivity.class);
	// intent.putExtra("id", friends_main.get(arg0).getId());
	// intent.putExtra("name", friends_main.get(arg0)
	// .getNickName());
	// intent.putExtra("head", friends_main.get(arg0).getHead());
	// startActivity(intent);
	// }
	// });
	// return convertView;
	// }
	//
	// }
}
